/**
 *  学习目标：Todos 案例
 */
import React, { useEffect, useState } from 'react';
import './styles/base.css';
import './styles/index.css';

export default function App() {
    // 列表数据
    const [list, setList] = useState(JSON
        .parse(localStorage.getItem('todu-list')) || [
            {
                id: 1,
                task: '学习React',
                isDone: false,
            },
            {
                id: 2,
                task: '学习Vue3',
                isDone: true,
            },
            {
                id: 3,
                task: '学习TS',
                isDone: false,
            },
        ])
    // 显示状态
    const [type, setType] = useState(JSON
        .parse(localStorage.getItem('todu-type')) || 'all')
    // 使用useEffect监听list的变化
    useEffect(() => {
        localStorage.setItem('todu-list', JSON.stringify(list))
    }, [list])
    useEffect(() => {
        localStorage.setItem('todu-type', JSON.stringify(type))
    }, [type])
    // 删除
    const handleDelById = (id) => {
        // console.log(id);
        setList(list.filter(item => item.id !== id))
    }
    // 修改选中状态
    const handleChange = (id) => {
        // const newList = list.map((item) => ({ ...item, isDone: item.id === id ? !item.isDone : item.isDone }))
        setList(list.map((item) => ({ ...item, isDone: item.id === id ? !item.isDone : item.isDone })))
    }
    // 清除已完成
    const handleClear = () => {
        setList(list.filter(item => !item.isDone))
    }
    // 统计剩余未完成的数量
    const count = list.filter(item => !item.isDone).length
    // 修改显示状态
    const setMyType = (type) => {
        setType(type)
    }
    // 根据状态，要显示的数据
    const showList = list.filter(item => {
        if (type === 'completed') return item.isDone
        if (type === 'active') return !item.isDone
        return true
    })
    const addList = (data) => {
        console.log(data);
        // 添加数据
        setList([{ id: Date.now(), task: data, isDone: false }, ...list])
    }
    // 全选状态
    const isAll = list.length ? list.every(item => item.isDone) : false
    // 全选按钮修改所有的状态
    const handleAll = (isChangeAll) => {
        setList(list.map(item => ({ ...item, isDone: isChangeAll })))
    }
    return (
        <section className="todoapp">
            {/* 头部 */}
            <Header addList={addList} ></Header>
            {/* 主体 */}
            <Main handleAll={handleAll} isAll={isAll} handleChange={handleChange} list={showList} handleDelById={handleDelById}></Main>
            {/* 底部 */}
            <Footer type={type} setMyType={setMyType} count={count} handleClear={handleClear}></Footer>
        </section>
    );

}


function Header({ addList }) {
    const [task, setTask] = useState('')
    const addEnter = (e) => {
        // console.log(e);
        // 回车，发请求
        if (e.keyCode === 13) {
            if (!task.trim()) {
                return alert('计划不能为空')
            }
            addList(task)
            // 清空
            setTask('')
        }
        // 按Esc清空数据
        if (e.keyCode === 27) {
            // 清空
            setTask('')
        }
    }
    return <header className="header">
        <h1>todos</h1>
        <input className="new-todo" onKeyDown={addEnter} onChange={(e) => setTask(e.target.value)} value={task} placeholder="需要做什么" autoFocus />
    </header>;
}
function Main({ list, handleDelById, handleChange, isAll, handleAll }) {
    return <section className="main">
        <input checked={isAll} id="toggle-all" onChange={() => handleAll(!isAll)} className="toggle-all" type="checkbox" />
        <label htmlFor="toggle-all">全选</label>
        <ul className="todo-list">
            {list.map(item => {
                return (
                    <li className={item.isDone ? "completed" : ''} key={item.id}>
                        <div className="view">
                            <input onChange={() => handleChange(item.id)} className="toggle" type='checkbox' checked={item.isDone} />
                            <label>{item.task}</label>
                            <button onClick={() => handleDelById(item.id)} className="destroy"></button>
                        </div>
                    </li>
                )
            })}
        </ul>
    </section>;
}


function Footer({ count, handleClear, setMyType, type }) {
    return <footer className="footer">
        <span className="todo-count">
            <strong>{count}</strong> 剩余
        </span>
        <ul className="filters">
            <li>
                <a onClick={() => setMyType('all')} className={type === 'all' ? "all selected" : 'all'} href="#/">
                    全部
                </a>
            </li>
            <li>
                <a onClick={() => setMyType('active')} className={type === 'active' ? "active selected" : 'active'} href="#/active">
                    未完成
                </a>
            </li>
            <li>
                <a onClick={() => setMyType('completed')} className={type === 'completed' ? "completed selected" : 'completed'} href="#/completed">
                    已完成
                </a>
            </li>
        </ul>
        <button onClick={handleClear} className="clear-completed">清除已完成</button>
    </footer>;
}
